package com.springboot.examples01.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.*;

import com.springboot.examples01.model.User;

@RestController
@RequestMapping("/users")
public class UserController {
	// 创建线程安全的map
	private static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

	@GetMapping("/")
	public List<User> getUser() {
		return new ArrayList<>(users.values());
	}

	@PostMapping("/")
	public String addUser(@RequestBody User user) {
		users.put(user.getId(), user);
		return "success";
	}

	@PutMapping("/{id}")
	public String updateUser(@PathVariable Long id, @RequestBody User user) {
		User u = users.get(id);
		if (null == u) {
			users.put(user.getId(), user);
		} else {
			u.setAge(user.getAge());
			u.setName(user.getName());
			users.put(id, u);
		}
		return "success";
	}

	@GetMapping("/{id}")
	public User getUser(@PathVariable Long id) {
		return users.get(id);
	}

	@DeleteMapping("/{id}")
	public String removeUser(@PathVariable Long id) {
		users.remove(id);
		return "success";
	}
}
